package com.yc.mvc.web;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器映射:
 *  1. @RestController + ModelAndView
 *      @RestController 标注的控制器, 其内部方法某返回值转成JSON ==> AJAX
 *      ModelAndView 方法特殊的返回值, 实现页面跳转
 *  2. @Controller + @ResponseBody
 *      @Controller 标注的控制器, 其内部方法默认进行页面跳转
 *      @ResponseBody 实现返回 JSON 数据 ==> AJAX
 */
@RestController
// 定义所有方法访问地址的同一前缀设置
@RequestMapping("page")
public class HelloAction {

    // 设置地址, 可以省去首字母的/
    // page/hello.do
    @RequestMapping("hello.do")
    public String hello(){
        return "hello world";
    }

    @RequestMapping(path="hello1.do",
            method = {RequestMethod.POST})
    String hello1(){
        return "hello1";
    }

    @GetMapping("hello2.do")
    String hello2(){
        return "hello2";
    }

    @PostMapping("hello3.do")
    String hello3(){
        return "hello3";
    }

    // 限定必须有a参数, 并且b参数必须=3
    @GetMapping(value = "add", params = {"a","b=3"})
    int add(int a, int b){
        return a + b;
    }

    @GetMapping(value = "add", params = {"a","b=3"},
        headers = {"Host=localhost"})
    int add1(int a, int b){
        return a + b + b;
    }
    /**
     * consumes 用于"限定"提交数据的类型
     * produces 用于设置返回的数据类型
     */
    @GetMapping(path = "hello.do",
        params = "name",
        produces = MediaType.TEXT_HTML_VALUE + ";charset=utf-8")
    // SpringMVC 默认将请求参数映射为方法参数, 名称匹配
    String hello( String name ){
        System.out.println("=====name=====" + name);
        return "hello " + name;
    }

    // 返回视图   page/tohome.do
    @GetMapping("tohome.do")
    ModelAndView tohome(){
        ModelAndView modelAndView = new ModelAndView(
                "redirect:../home.html");
        return modelAndView;
    }


}
